from django.contrib import admin
from blog.models import Post


class BaseOwnerAdmin(admin.ModelAdmin):
    """
    1. 用来处理文章、分类、标签 model的 owner 字段自动填充
    2. 用来针对 queryset 过滤当前用户的数据
    """
    exclude = ('owner', )

    def get_queryset(self, request):
        qs = super(BaseOwnerAdmin, self).get_queryset(request)
        print(qs.model)
        if qs.model.__name__ == "Post":
            print("model is Post")
            return qs.filter(author=request.user)
        return qs.filter(owner=request.user)

    def save_model(self, request, obj, form, change):
        if isinstance(obj, Post):
            obj.author = request.user
        obj.owner = request.user
        return super(BaseOwnerAdmin, self).save_model(request, obj, form, change)
